import Vue from 'vue'
import Vuex from 'vuex'
import Cookie from 'js-cookie'

Vue.use(Vuex)

require('whatwg-fetch')

export const state = () => ({
    authToken: "",
    userInfo:""
})

export const mutations = {
    setUserInfo: function(state, userinfo){
        state.userInfo = userinfo
    },
    setAuthToken: function(state, token){
      state.authToken = token.access_token
      state.userInfo = token.user
      Cookie.set("access_token",token.access_token)
      Cookie.set("refresh_token",token.refresh_token)
      window.localStorage.setItem("access_token", token.access_token)
      window.localStorage.setItem("refresh_token", token.refresh_token)
    },
    clearAuthToken : function(state){
      state.authToken = ""
      state.userInfo = ""
      Cookie.remove("access_token")
      Cookie.remove("refresh_token")
      window.localStorage.removeItem("access_token")
      window.localStorage.removeItem("refresh_token")
    }

}

export const actions = {
    nuxtServerInit({commit}, { req }) {
      commit('setUserInfo', req.session.userInfo)
    },
    login({ commit }, token) {
      commit('setAuthToken', token)
    },  
    logout({ commit }) {
      commit('clearAuthToken')
    }  
}

const createStore = () => {
    return new Vuex.Store({
        state,
        mutations,
        actions
    })
}

export default createStore